import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_json_view/flutter_json_view.dart';
import 'package:flutter_redis/pages/redis_query_result_page_controller.dart';
import 'package:get/get.dart';
import 'package:toastification/toastification.dart';

class RedisQueryResultPage extends StatelessWidget {
  const RedisQueryResultPage({super.key});

  @override
  Widget build(BuildContext context) {
    final controller = Get.put(RedisQueryResultPageController());
    final value = Get.arguments;

    return Scaffold(
      appBar: AppBar(
        title: Text('查询'),
        actions: [
          IconButton(
            onPressed: () {
              Map<String, dynamic> data = jsonDecode(value);
              data.keys;
              showModalBottomSheet(
                context: context,
                shape: const RoundedRectangleBorder(
                  borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
                ),
                showDragHandle: true,
                builder: (BuildContext context) {
                  return SizedBox(
                    height: 150,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        ListTile(
                          leading: const Icon(Icons.copy_all_outlined),
                          title: const Text('复制全部'),
                          onTap: () {
                            Clipboard.setData(ClipboardData(text: value));
                            toastification.show(
                              context: context,
                              type: ToastificationType.info,
                              style: ToastificationStyle.simple,
                              alignment: Alignment.topCenter,
                              autoCloseDuration: const Duration(seconds: 2),
                              title: Text('已复制全部内容到剪贴板'),
                            );
                            Navigator.pop(context);
                          },
                        ),
                        ListTile(
                          leading: const Icon(Icons.copy_outlined),
                          title: const Text('复制指定key'),
                          onTap: () {
                            Navigator.pop(context);
                            Map<String, dynamic> data = jsonDecode(value);
                            List<KeyNode> roots = buildKeyTreeList(data, '');
                            showDialog(
                              context: context,
                              builder: (BuildContext context) {
                                return AlertDialog(
                                  title: const Text('选择要复制的Key'),
                                  content: SizedBox(
                                    width: double.maxFinite,
                                    height: 400,
                                    child: SingleChildScrollView(
                                      child: _KeyTreeListWidget(
                                        nodes: roots,
                                        onCopy: (String keyPath) {
                                          var keyValue = getValueByPath(
                                            data,
                                            keyPath,
                                          );
                                          String prettyJson;
                                          try {
                                            prettyJson =
                                                const JsonEncoder.withIndent(
                                                  '  ',
                                                ).convert(keyValue);
                                          } catch (e) {
                                            prettyJson = keyValue.toString();
                                          }
                                          Clipboard.setData(
                                            ClipboardData(text: prettyJson),
                                          );
                                          Navigator.pop(context);
                                          toastification.show(
                                            context: context,
                                            type: ToastificationType.info,
                                            style: ToastificationStyle.simple,
                                            alignment: Alignment.topCenter,
                                            autoCloseDuration: const Duration(
                                              seconds: 2,
                                            ),
                                            title: Text('已复制 $keyPath 的内容到剪贴板'),
                                          );
                                        },
                                      ),
                                    ),
                                  ),
                                );
                              },
                            );
                          },
                        ),
                      ],
                    ),
                  );
                },
              );
            },
            icon: Icon(Icons.copy_rounded),
          ),
        ],
      ),
      body: SafeArea(
        child: Container(
          color: Colors.white,
          child: JsonView.string(
            value,
            theme: JsonViewTheme(
              backgroundColor: Colors.white,
              keyStyle: TextStyle(
                color: Colors.black54,
                fontSize: 16,
                fontWeight: FontWeight.w600,
              ),
              doubleStyle: TextStyle(color: Colors.green, fontSize: 16),
              intStyle: TextStyle(color: Colors.green, fontSize: 16),
              stringStyle: TextStyle(color: Colors.green, fontSize: 16),
              boolStyle: TextStyle(color: Colors.green, fontSize: 16),
              closeIcon: Icon(
                Icons.expand_less_outlined,
                color: Colors.black,
                size: 20,
              ),
              openIcon: Icon(
                Icons.expand_more_outlined,
                color: Colors.black,
                size: 20,
              ),
              separator: Padding(
                padding: EdgeInsets.symmetric(horizontal: 8.0),
                child: Text(
                  ":",
                  style: TextStyle(
                    color: Colors.black54,
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

// ====== 以下为KeyNode和树形选择组件 ======
class KeyNode {
  final String name;
  final String path;
  final List<KeyNode> children;
  KeyNode(this.name, this.path, [this.children = const []]);
}

KeyNode buildKeyTree(dynamic node, String path, String name) {
  if (node is Map<String, dynamic>) {
    return KeyNode(
      name,
      path,
      node.entries
          .map(
            (e) => buildKeyTree(
              e.value,
              path.isEmpty ? e.key : '$path.${e.key}',
              e.key,
            ),
          )
          .toList(),
    );
  } else if (node is List) {
    return KeyNode(
      name,
      path,
      List.generate(
        node.length,
        (i) =>
            buildKeyTree(node[i], path.isEmpty ? '[$i]' : '$path[$i]', '[$i]'),
      ),
    );
  } else {
    return KeyNode(name, path, []);
  }
}

// 新增：支持多根节点的树构建
List<KeyNode> buildKeyTreeList(dynamic node, String path) {
  if (node is Map<String, dynamic>) {
    return node.entries
        .map(
          (e) => buildKeyTree(
            e.value,
            path.isEmpty ? e.key : '$path.${e.key}',
            e.key,
          ),
        )
        .toList();
  } else if (node is List) {
    return List.generate(
      node.length,
      (i) => buildKeyTree(node[i], path.isEmpty ? '[$i]' : '$path[$i]', '[$i]'),
    );
  } else {
    return [];
  }
}

dynamic getValueByPath(dynamic node, String path) {
  var parts = RegExp(
    r'([^\.\[\]]+)|(\[\d+\])',
  ).allMatches(path).map((m) => m.group(0)!).toList();
  dynamic current = node;
  for (var part in parts) {
    if (part.startsWith('[') && part.endsWith(']')) {
      int idx = int.parse(part.substring(1, part.length - 1));
      if (current is List && idx < current.length) {
        current = current[idx];
      } else {
        return null;
      }
    } else {
      if (current is Map<String, dynamic> && current.containsKey(part)) {
        current = current[part];
      } else {
        return null;
      }
    }
  }
  return current;
}

class _KeyTreeWidget extends StatefulWidget {
  final KeyNode node;
  final Function(String keyPath) onCopy;
  const _KeyTreeWidget({required this.node, required this.onCopy});
  @override
  State<_KeyTreeWidget> createState() => _KeyTreeWidgetState();
}

class _KeyTreeWidgetState extends State<_KeyTreeWidget> {
  final Map<String, bool> _expanded = {};
  @override
  Widget build(BuildContext context) {
    return _buildNode(widget.node, 0);
  }

  Widget _buildNode(KeyNode node, int depth) {
    if (node.children.isEmpty) {
      // 叶子节点，显示完整路径，缩进为 depth+1
      return ListTile(
        contentPadding: EdgeInsets.only(left: 16.0 * (depth + 1)),
        title: Text(node.path),
        onTap: () => widget.onCopy(node.path),
      );
    } else {
      bool expanded = _expanded[node.path] ?? true;
      return ExpansionTile(
        key: PageStorageKey(node.path),
        title: Padding(
          padding: EdgeInsets.only(left: 16.0 * depth),
          child: Text(node.name),
        ),
        initiallyExpanded: expanded,
        children: node.children
            .map<Widget>((child) => _buildNode(child, depth + 1))
            .toList(),
        onExpansionChanged: (val) {
          setState(() {
            _expanded[node.path] = val;
          });
        },
      );
    }
  }
}

// 新增：多根节点树形Widget
class _KeyTreeListWidget extends StatelessWidget {
  final List<KeyNode> nodes;
  final Function(String keyPath) onCopy;
  const _KeyTreeListWidget({required this.nodes, required this.onCopy});
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: nodes
          .map((n) => _KeyTreeWidget(node: n, onCopy: onCopy))
          .toList(),
    );
  }
}
